import reqwest from 'reqwest';
import _ from 'lodash';
import requestHandlers from './requestHandlers.js';

let globalConfig = {};
let defaultsConfig = {};
let postConfig = {
    method: "POST",
    contentType: "application/json"
}
let getConfig = {
    method: "GET",
    contentType: "application/json"
}

/**
 * options:
 *  url a fully qualified uri
 *  method http method (default: GET)
 *  headers http headers (default: {})
 *  data entity body for PATCH, POST and PUT requests. Must be a query String or JSON object
 *  type a string enum. html, xml, json, or jsonp. Default is inferred by resource extension. Eg: .json will set type to json. .xml to xml etc.
 *  contentType sets the Content-Type of the request. Eg: application/json
 *  crossOrigin for cross-origin requests for browsers that support this feature.
 *  success A function called when the request successfully completes
 *  error A function called when the request fails.
 *  complete A function called whether the request is a success or failure. Always called when complete.
 *  before A function called before request
 *  jsonpCallback Specify the callback function name for a JSONP request. This value will be used instead of the random (but recommended) name automatically generated by reqwest.
 */
let request = (options) => {
    let options = _.assign({}, defaultsConfig, globalConfig, options);

    if (options.before && !options.before(options))
        return new Promise();
    requestHandlers.beforeHandle(options);

    return reqwest(options)
        .then(res => requestHandlers.successHandle)
        .fail(res => requestHandlers.errorHandle)
        .always(res => requestHandlers.completeHandle);
}

let post = (url, data, options) => {
    options.url = url;
    options.data = data;
    options = _.assign({},postConfig,options);
    return request(options);
}

let get = (url,data,options)=>{
    options.url = url;
    options.data = data;
    options = _.assign({},getConfig,options);
    return request(options);
}

export default{
    request,
    post,
    get
}